<?php namespace App\Admin\Access\Operation;

//基础条件
use App\Core\Repository\Criterias\PaginateCriteria;
//过滤器
use App\Core\Repository\Criterias\Filters\InputKeywordsCriteria;
use App\Core\Repository\Criterias\Filters\InputCriteria;
use Input;

//操作组
use App\Admin\Access\OperationGroup\Repository as OperationGroup;

trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
    
    protected function bootService(){
        $this->bootBaseService();
        $this->setRepository(new Repository);
        $this->setMeta(new Meta);
        $this->repository = $this->getRepository();
        //添加观察者
        $this->addListeners([
            new Listeners\CreateListener(),
            new Listeners\UpdateListener()
        ]);
    }
    
    protected function groupLists(){
        $operationGroup =  new OperationGroup();
        return $operationGroup->all('name', 'group_id');
    }
	
    //列表
    public function lists(){
        //过滤器
        $conditions = [
            new InputKeywordsCriteria('name'),
            new InputCriteria('group_id')
        ];
        $count = $this->repository->addCriterias($conditions)->count();
        $conditions[] = new PaginateCriteria();
        $data = $this->repository->resetQuery()->resetCriteria()->addCriterias($conditions)->with('group')->all();
        return $this->success([
            'count' => $count,
            'data' => $data
        ]);
    }
    
    //批量添加
    public function multiAdd(){
        $groupId = Input::get('group_id', '');
		$itemsJson = Input::get('items', '');
		$items = json_decode($itemsJson, true);
		//参数验证
		if(!is_numeric($groupId) || !$items){
			return $this->error('参数有误');
		}
		$datas = [];
		foreach($items as $item){
			$datas[] = [
				'group_id' => $groupId,
				'name' => $item['name'],
				'code' => $item['code'],
                'log_config' => json_encode([
                    'data_source' => $item['data_source'],
                    'data_id' => $item['data_id'],
                    'data_name' => $item['data_name']
                ])
			];
		}
        foreach($datas as $item){
            $this->repository->create($item);
        }
        return $this->success();
    }
}